package com.haibei.view.web;

import java.util.UUID;

import com.haibei.App;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

/**
 * 产生UUID，按照传入的参数截取,去掉"-"符号。如： <br/>
 * UUID:5cbad77c-0aa2-4704-911a-7ae31889b1a6 传入参数是10，结果为：5cbad77c0a
 * 
 */
public class UUIDUtils {

	private static final String TAG = App.tag;
	/**
	 * 存入Preferences中uniqueId的key
	 */
	public static final String PREFERENCE_DUMPCATCHER_CLIENT = "dumpcatcher_client";

	/**
	 * 存入Preferences中设备did的key
	 */
	public static final String PREFERENCE_DEVICES_DID = "devices_did";

	/**
	 * 获取uuid，并截取number
	 * 
	 * @param number
	 *            要截取的位数
	 * @return 截取后的随机数
	 */
	public static String getUUID(int number) {

		String uuidstr;

		try {
			UUID uuid = UUID.randomUUID();

			uuidstr = uuid.toString();

			uuidstr = uuidstr.substring(0, 8) + uuidstr.substring(9, 13) + uuidstr.substring(14, 18)
					+ uuidstr.substring(19, 23) + uuidstr.substring(24);

			if (uuidstr.length() > number) {
				uuidstr = uuidstr.substring(0, number);
			}
			// 去掉"-"符号

		} catch (Exception e) {
			Log.e(TAG, "get uuid exception : ", e);
			return null;
		}

		return uuidstr;

	}

	/**
	 * 创建唯一的序列号UUID
	 * 
	 * @param preferences
	 * @return 设备uniqueId
	 */
	public static String createUniqueId(SharedPreferences preferences) {
		String uniqueId = preferences.getString(PREFERENCE_DUMPCATCHER_CLIENT, null);
		if (uniqueId == null) {
			uniqueId = UUID.randomUUID().toString();
			Editor editor = preferences.edit();
			editor.putString(PREFERENCE_DUMPCATCHER_CLIENT, uniqueId);
			editor.commit();
		}
		return uniqueId;
	}

	/**
	 * 得到设备did
	 * 
	 * @param preferences
	 * @return 设备did
	 */
	public static String getUniqueDid(SharedPreferences preferences) {
		return preferences.getString(PREFERENCE_DEVICES_DID, null);
	}

	/**
	 * 创建设备id
	 * 
	 * @param preferences
	 * @param uniqueDid
	 * @return 设备id
	 */
	public static String createUniqueDid(SharedPreferences preferences, String uniqueDid) {
		Editor editor = preferences.edit();
		editor.putString(PREFERENCE_DEVICES_DID, uniqueDid);
		editor.commit();
		return uniqueDid;
	}

}